//
//  GridView.swift
//  ZLKit_SwiftDemo_Example
//
//  Created by itzhaolei on 2022/1/17.
//  Copyright © 2022 CocoaPods. All rights reserved.
//

import SnapKit

open class ZLGridView: UIStackView {
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    private var column: Int = 0
    private var columnSpace: CGFloat = 0
    private var rowSpace: CGFloat = 0
    private var itemBgColor: UIColor = .white
    private var getItem: Basic_return<ZLGridUnitView> = nil
    private var fillItemData: Params_two_void<ZLGridUnitView, Int> = nil
    private var click: Params_one_void<Int> = nil
    public convenience init(column: Int = 3, columnSpace: CGFloat = 10, rowSpace: CGFloat = 10, itemBgColor: UIColor = .white, getItem: Basic_return<ZLGridUnitView>, fillItemData: Params_two_void<ZLGridUnitView, Int>, click: Params_one_void<Int>) {
        self.init(frame: .zero)
        self.column = column
        self.columnSpace = columnSpace
        self.rowSpace = rowSpace
        self.itemBgColor = itemBgColor
        self.getItem = getItem
        self.fillItemData = fillItemData
        self.click = click
        spacing = columnSpace
        axis = .vertical
        distribution = .fillEqually
    }
    
    required public init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 刷新数据
    public func reloadData(itemCount: Int = 0) {
        var viewsCount = 0
        for view in subviews {
            viewsCount += view.subviews.count
        }
        let estimateCount = Int(ceil(Double(itemCount) / Double(column))) * column
        var maxCount = viewsCount > itemCount ? viewsCount : itemCount
        maxCount = maxCount > estimateCount ? maxCount : estimateCount
        for index in 0..<maxCount {
            var hStackView: UIStackView = .init()
            // 查找或新建对应的单元容器
            if index < (subviews.count * column) {
                let hStackIndex = Int(floor(Double(index) / Double(column)))
                hStackView = subviews[hStackIndex] as? UIStackView ?? .init()
            }else {
                hStackView.axis = .horizontal
                hStackView.spacing = rowSpace
                hStackView.distribution = .fillEqually
                addArrangedSubview(hStackView)
            }
            // 查找或新建对应的单元视图
            var view: ZLGridUnitView = getItem?() ?? .init()
            if index < viewsCount {
                view = hStackView.subviews[index%column] as? ZLGridUnitView ?? .init()
            }else {
                view.contentView.backgroundColor = itemBgColor
                hStackView.addArrangedSubview(view)
            }
            // 重置
            view.contentView.isHidden = true
            if hStackView.subviews.first == view {
                hStackView.isHidden = true
            }
            // 赋值
            if index < itemCount {
                view.contentView.isHidden = false
                hStackView.isHidden = false
                fillItemData?(view, index)
                // 监听点击事件
                view.touch = {[weak self] index in
                    self?.click?(index)
                    self?.reloadData(itemCount: itemCount)
                }
            }
            view.layoutIfNeeded()
        }
    }
    
}

open class ZLGridUnitView: UIView {
    
    public var isSelected: Bool = false
    
    /// 点击事件
    public var touch: Params_one_void<Int> = nil {
        didSet {
            contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapAction)))
        }
    }
    
    /// 内容视图
    public lazy var contentView: UIView  = {
        let view = UIView()
        return view
    }()
    
    override public init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(contentView)
        contentView.snp.makeConstraints {
            $0.edges.equalToSuperview()
        }
    }
    
    required public init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func tapAction() {
        let thisIndex = superview?.subviews.firstIndex(of: self) ?? 0
        let parentIndex = superview?.superview?.subviews.firstIndex(of: self.superview ?? .init()) ?? 0
        let dynamicColumnCount = superview?.subviews.count ?? 0
        let index = parentIndex * dynamicColumnCount + thisIndex
        touch?(index)
    }

    /// 获取当前索引
    public func getCurrentIndex() -> Int {
        let thisIndex = superview?.subviews.firstIndex(of: self) ?? 0
        let parentIndex = superview?.superview?.subviews.firstIndex(of: self.superview ?? .init()) ?? 0
        let dynamicColumnCount = superview?.subviews.count ?? 0
        let index = parentIndex * dynamicColumnCount + thisIndex
        return index
    }
    
}
